#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/15 18:00
# @Author : 闫峰
# @File    : view.py
import datetime
import json
from urllib import parse
import random
import re
import time
import uuid
from flask import request, Response, jsonify, Request

from service.area_ap_manager.v1_apis import AreaApManagerApis
from service.charge.v1_apis import ChargeApis
from utils.functions_control import get_uuid
from utils.handler_request_log import handler_request_log
from utils.model import RedisData, StatusTypes
from utils.mongodb_utils import MongoDBLink
from utils.redis_operations import RedisOperator
from utils.time_control import count_time

user = parse.quote_plus("viviu")
passwd = parse.quote_plus("viu@1234")
sit_charge_mock_data_modb = MongoDBLink(
    uri=f'mongodb://{user}:{passwd}@10.86.3.113:27017/?authSource=admin',
    dbname='sit_charge_mock_data', coll_name='sit_charge_mock_data')
redis_op = RedisOperator()
@count_time
def v1_aapmgr(path):
    is_forward = True
    path = "/v1/aapmgr/" + path
    request_method = request.method
    # 使用示例
    key = "/v1/aapmgr"+"/"+request_method
    value = redis_op.hgetall(key)
    redis_data = None
    if value:
        if key.split('/')[-1].upper() == request_method:
            redis_data = RedisData(**value)
            if redis_data.status_type.value in [StatusTypes.Forwarded_500.value, StatusTypes.Forwarded.value]:
                is_forward = False
    sit_base_url = "http://cg-sit-auto-zone.yuntiancloud.com/area-ap-manager" + path
    try:
        request_json = request.json
    except:
        request_json = None
    try:
        request_args = dict(request.args)
    except:
        request_args = None

    resp_json = None
    response = None
    if is_forward:
        status_code,resp_json = AreaApManagerApis.v1_aapmgr_handler(request_method, sit_base_url, request_json,request_args)
        if redis_data:
            if redis_data.time_count != "0":
                time.sleep(int(redis_data.timeout))
                time_count = int(redis_data.time_count) - 1
                redis_op.hset(name=key,key="time_count",value=time_count)
        response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
    else:
        if redis_data:
            if redis_data.status_type.value == StatusTypes.Forwarded_500.value:
                status_code = random.choice([500])
                match status_code:
                    case 500:
                        resp_json = {
                            "ret": {
                                "code": status_code,
                                "reason": f"{path}调用失败",
                                "msg": f"{path}调用失败",
                                "request_id": str(get_uuid()),
                            }
                        }
                        resp_str = json.dumps(resp_json)
                        response = Response(resp_str, status=status_code, mimetype='application/json')
            elif redis_data.status_type.value == StatusTypes.Forwarded.value:
                pass
    handler_request_log(request,status_code,resp_json,sit_charge_mock_data_modb,bool(request_json))
    return response

def v1_status(path):
    is_forward = True
    path = "/v1/status/" + path
    # 使用示例
    value = redis_op.get_key(path)
    if value == "1":
        is_forward = False
    sit_base_url = "http://cg-sit-auto-zone.yuntiancloud.com/area-ap-manager" + path
    try:
        request_json = request.json
    except:
        request_json = None
    try:
        request_args = dict(request.args)
    except:
        request_args = None
    request_method = request.method
    resp_json = None
    response = None
    if is_forward:
        status_code,resp_json = AreaApManagerApis.v1_status_handler(request_method, sit_base_url, request_json,request_args)
        response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
    else:
        status_code = random.choice([500])
        match status_code:
            case 500:
                resp_json = {
                    "ret": {
                        "code": status_code,
                        "reason": f"{path}调用失败",
                        "msg": f"{path}调用失败",
                        "request_id": str(get_uuid()),
                    }
                }
                resp_str = json.dumps(resp_json)
                response = Response(resp_str, status=status_code, mimetype='application/json')
    handler_request_log(request,status_code,resp_json,sit_charge_mock_data_modb,bool(request_json))
    return response

def v1_config(path):
    is_forward = True
    path = "/v1/config/" + path
    # 使用示例
    value = redis_op.get_key(path)
    if value == "1":
        is_forward = False
    sit_base_url = "http://cg-sit-auto-zone.yuntiancloud.com/area-ap-manager" + path
    try:
        request_json = request.json
    except:
        request_json = None
    try:
        request_args = dict(request.args)
    except:
        request_args = None
    request_method = request.method
    resp_json = None
    response = None
    if is_forward:
        status_code,resp_json = AreaApManagerApis.v1_config_handler(request_method, sit_base_url, request_json,request_args)
        response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
    else:
        status_code = random.choice([500])
        match status_code:
            case 500:
                resp_json = {
                    "ret": {
                        "code": status_code,
                        "reason": f"{path}调用失败",
                        "msg": f"{path}调用失败",
                        "request_id": str(get_uuid()),
                    }
                }
                resp_str = json.dumps(resp_json)
                response = Response(resp_str, status=status_code, mimetype='application/json')
    handler_request_log(request,status_code,resp_json,sit_charge_mock_data_modb,bool(request_json))
    return response

def v1_db(path):
    is_forward = True
    path = "/v1/db/" + path
    # 使用示例
    value = redis_op.get_key(path)
    if value == "1":
        is_forward = False
    sit_base_url = "http://cg-sit-auto-zone.yuntiancloud.com/area-ap-manager" + path
    try:
        request_json = request.json
    except:
        request_json = None
    try:
        request_args = dict(request.args)
    except:
        request_args = None
    request_method = request.method
    resp_json = None
    response = None
    if is_forward:
        status_code,resp_json = AreaApManagerApis.v1_db_handler(request_method, sit_base_url, request_json,request_args)
        response = Response(json.dumps(resp_json), status=200, mimetype='application/json')
    else:
        status_code = random.choice([500])
        match status_code:
            case 500:
                resp_json = {
                    "ret": {
                        "code": status_code,
                        "reason": f"{path}调用失败",
                        "msg": f"{path}调用失败",
                        "request_id": str(get_uuid()),
                    }
                }
                resp_str = json.dumps(resp_json)
                response = Response(resp_str, status=status_code, mimetype='application/json')
    handler_request_log(request,status_code,resp_json,sit_charge_mock_data_modb,bool(request_json))
    return response